<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-select v-model="listQuery.userId" :placeholder="$t('请输入用户账号')" clearable style="width: 200px;" class="filter-item" filterable >
        <el-option v-for="item in userOptions" :key="item.id" :label="item.username" :value="item.id">
        </el-option>
      </el-select>
      <el-input v-model="listQuery.orderSn" clearable class="filter-item" style="width: 200px;"
        :placeholder="$t('Please_enter_order_number')" />
      <el-select v-model="listQuery.shopId" clearable style="width: 200px" class="filter-item"
        :placeholder="$t('Please_select_store_')">
        <el-option v-for="item in shops" :label="item.name" :value="item.id" />
      </el-select>
      <el-select v-model="listQuery.orderStatusArray" multiple style="width: 200px" class="filter-item"
        :placeholder="$t('Please_select_order_status')">
        <el-option v-for="(key, value) in statusMap" :key="key" :label="key" :value="value" />
      </el-select>
      <el-date-picker
        style="vertical-align: top; width:385px;"
        v-model="listQuery.dateRange"
        type="daterange"
        :picker-options="pickerOptions"
        @change="changeDate"
        format="yyyy-MM-dd HH:mm:ss"
        value-format="yyyy-MM-dd HH:mm:ss"
        range-separator="——"
        :start-placeholder="$t('开始日期')"
        :end-placeholder="$t('结束日期')">
      </el-date-picker>
      <el-select v-model="listQuery.payType" multiple placeholder="请选择支付方式">
        <el-option
            v-for="item in payTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
      <el-select v-model="listQuery.orderSource" multiple placeholder="请选择订单来源">
        <el-option
            v-for="item in orderSources"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="info" icon="el-icon-search" @click="handleFilter">{{ $t('Search') }}
      </el-button>
      <!--      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">{{$t('Find')}}</el-button>-->
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" :element-loading-text="$t('Searching')" border fit stripe
              :header-cell-style="{background:'#414444',color:'#ffffff',top:'5px','font-size':'15px'}"
      highlight-current-row>
      <el-table-column align="center" type="index" :label="$t('排序')" :index="getIndex" width="60"></el-table-column>
      <el-table-column align="center" type="expand" :label="$t('订单商品')" width="100">
        <template slot-scope="scope">
          <el-descriptions v-for="(goods,index) in scope.row.orderGoods" direction="vertical" :column="10" border>
            <el-descriptions-item label="排序">{{index+1}}</el-descriptions-item>
            <el-descriptions-item label="商品编号">{{goods.goodsSn}}</el-descriptions-item>
            <el-descriptions-item :labelStyle="{'width': '250px'}" label="商品名称">{{goods.goodsName}}</el-descriptions-item>
            <el-descriptions-item label="商品图片">
              <template slot="label">
                {{$t('商品图片')}}
                <i class="el-icon-thumb"></i>
              </template>
              <el-popover placement="right" trigger="click">
                <el-image style="width: 300px;border-radius: 3px" :src="goods.picUrl" fit="contain"></el-image>
                <el-image slot="reference" preview-src-list style="border-radius:5%;width:80px" :src="goods.picUrl"  width="20" lazy>
                  <div slot="error" class="image-slot" style="border-radius:5%;">
                    <i style="font-size: 60px;border-radius:5%;" class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </el-popover>
            </el-descriptions-item>
            <el-descriptions-item label="购买数量">{{goods.number}}</el-descriptions-item>
            <el-descriptions-item label="商品税价">${{goods.taxPrice}}</el-descriptions-item>
            <el-descriptions-item label="商品单价">${{goods.unitPrice}}</el-descriptions-item>
            <el-descriptions-item label="税前总金额">${{goods.sellingPrice}}</el-descriptions-item>
            <el-descriptions-item label="商品总价">${{goods.price}}</el-descriptions-item>
            <el-descriptions-item label="商品规格"><el-tag >{{goods.specifications}}</el-tag></el-descriptions-item>
          </el-descriptions>
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="100" :label="$t('Order_ID')" prop="orderSn" />

      <el-table-column align="center" min-width="100" :label="$t('Store')" prop="shopId">
        <template slot-scope="scope">
          {{ getShopName(scope.row.shopId) }}
        </template>
      </el-table-column>

      <el-table-column align="center" min-width="100" :label="$t('Submission_time')" prop="addTime" >
        <template slot-scope="scope">
          {{ JSON.stringify(scope.row.addTime)}}
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="100" :label="$t('支付时间')" prop="payTime" >
        <template slot-scope="scope">
          {{ JSON.stringify(scope.row.payTime)}}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('Staff_name')" prop="username" />

      <el-table-column align="center" :label="$t('Order_cost')" prop="orderPrice">
        <template slot-scope="scope">
          {{ priceOrPoint(scope.row) }}
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('Payment_method')" prop="payType">
        <template slot-scope="scope">
          <el-tag type="info" effect="plain1">{{ payTypeFilter(scope.row.payType)||this.$t('未支付') }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('Source_of_order')" prop="orderSource">
        <template slot-scope="scope">
          <el-tag type="info" effect="plain1">{{ orderSourceFilter(scope.row.orderSource) }}</el-tag>
        </template>
      </el-table-column>

      <!--<el-table-column align="center" :label="$t('Member_ID')" prop="userId"/>-->

      <el-table-column align="center" :label="$t('Order_status')" prop="orderStatus">
        <template slot-scope="scope">
          <el-tag :type="scope.row.orderStatus==201?'success':'danger'" effect="dark">{{ orderStatusFilter(scope.row.orderStatus) }}</el-tag>
        </template>
      </el-table-column>

      <!-- <el-table-column align="center" :label="$t('Order_type')" prop="orderType">
        <template slot-scope="scope">
          <el-tag>{{ orderTypeFilter(scope.row.orderType)  }}</el-tag>
        </template>
      </el-table-column> -->

      <!--      <el-table-column align="center" label="订单金额" prop="orderPrice"/>

      <el-table-column align="center" label="支付金额" prop="actualPrice"/>

      <el-table-column align="center" label="支付时间" prop="payTime"/>

      <el-table-column align="center" label="物流单号" prop="shipSn"/>

      <el-table-column align="center" label="物流渠道" prop="shipChannel"/>-->

      <el-table-column align="center"  :label="$t('Operate')" class-name="small-padding fixed-width"  width="150">
        <template slot="header" slot-scope="{row}">
          {{$t('Operate')}}
          <i class="el-icon-setting"style="color: #d35e32"></i>
        </template>
        <template slot-scope="scope">
          <el-row>
          <el-button icon="el-icon-view" type="info" plain1 size="mini" @click="handleDetail(scope.row)" >{{ $t('Details') }}</el-button>
          <el-button icon="el-icon-s-promotion"  v-permission="['GET /admin/p/order_order_delivery']"
            v-if="scope.row.orderStatus == 201 && scope.row.refundStatus != 1" type="success" plain1 size="mini"
            @click="handleShip(scope.row)">{{ $t('Delivery_') }}</el-button>
          <el-button ref="handleRefund" icon="el-icon-refresh-left" plain1 v-permission="['POST /admin/p/order_order_refund']" size="mini" v-if="scope.row.orderStatus == 202"
            type="warning" @click="handleRefund(scope.row)" >{{ $t('退款') }}</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 订单详情对话框 -->
    <el-dialog :visible.sync="orderDialogVisible" :title="$t('Order_details')" width="800">

      <el-form :data="orderDetail" label-position="left">
        <el-form-item :label="$t('Order_ID')">
          <span>{{ orderDetail.order.orderSn }}</span>
        </el-form-item>
        <el-form-item :label="$t('Order_status')">
          <el-tag>{{ orderStatusFilter(orderDetail.order.orderStatus) }}</el-tag>
        </el-form-item>
        <el-form-item :label="$t('订单用户')">
          <span>{{ orderDetail.user.nickname }}</span>
        </el-form-item>
        <el-form-item :label="$t('用户留言')">
          <span>{{ orderDetail.order.message }}</span>
        </el-form-item>
        <el-form-item :label="$t('Receiving_details')">
          <span>（{{ $t('Receiver_') }}）{{ orderDetail.order.consignee }}</span>
          <span>（{{$t('手机号')}}）{{ orderDetail.order.mobile }}</span>
          <span>（{{$t('地址')}}）{{ orderDetail.order.address }}</span>
        </el-form-item>
        <el-form-item :label="$t('Goods_details_info')">
          <el-table :data="orderDetail.orderGoods" border fit highlight-current-row>
            <el-table-column align="center" :label="$t('Merchandise_name')" prop="goodsName" />
            <el-table-column align="center" :label="$t('Merchandise_code')" prop="goodsSn" />
            <el-table-column align="center" :label="$t('Merchandise_specifications')" prop="specifications" />
            <el-table-column align="center" :label="$t('Merchandise_price')" prop="price" />
            <el-table-column align="center" :label="$t('Number_of_merchandise')" prop="number" />
            <el-table-column align="center" :label="$t('Merchandise_picture')" prop="picUrl">
              <template slot-scope="scope">
                <img :src="scope.row.picUrl" width="40">
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item :label="$t('Cost_details')">
          <span>
            ({{ $t('实际费用') }}){{ orderDetail.order.actualPrice }}{{ $t('Dollars') }}=
            ({{ $t('Merchandise_total_cost') }}){{ orderDetail.order.goodsPrice }}{{ $t('Dollars') }}+
            ({{ $t('快递费用') }}){{ orderDetail.order.freightPrice }}{{ $t('Dollars') }}-
            ({{ $t('优惠减免') }}){{ orderDetail.order.couponPrice }}{{ $t('Dollars') }}-
            ({{ $t('积分减免') }}){{ orderDetail.order.integralPrice }}{{ $t('Dollars') }}
          </span>
        </el-form-item>
        <el-form-item label="支付信息">
          <span>（{{ $t('支付渠道') }}）{{ $t('微信支付') }}</span>
          <span>（{{ $t('支付时间') }}）{{ orderDetail.order.payTime }}</span>
        </el-form-item>
        <el-form-item label="快递信息">
          <span>（{{ $t('Express_Delivery_Company') }}）{{ orderDetail.order.shipChannel }}</span>
          <span>（{{ $t('快递单号') }}）{{ orderDetail.order.shipSn }}</span>
          <span>（{{ $t('发货时间') }}）{{ orderDetail.order.shipTime }}</span>
        </el-form-item>
        <el-form-item :label="$t('Receiving_details')">
          <span>（{{ $t('确认收货时间') }}）{{ orderDetail.order.confirmTime }}</span>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 发货对话框 -->
    <el-dialog :visible.sync="shipDialogVisible" :title="$t('Delivery_')">
      <el-form ref="shipForm" :model="shipForm" status-icon label-position="left" label-width="100px"
        style="width: 400px; margin-left:50px;">
        <el-form-item :label="$t('Express_Delivery_Company')" prop="shipChannel">
          <el-input v-model="shipForm.shipChannel" />
        </el-form-item>
        <el-form-item :label="$t('Express_Delivery_number')" prop="shipSn">
          <el-input v-model="shipForm.shipSn" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain1 round icon="el-icon-error" @click="shipDialogVisible = false">{{ $t('Cancel') }}</el-button>
        <el-button plain1 round icon="el-icon-success" type="primary" @click="confirmShip">{{ $t('Confirm') }}</el-button>
      </div>
    </el-dialog>

    <!-- 退款对话框 -->
    <el-dialog :visible.sync="refundDialogVisible" :title="$t('退款')">
      <el-form ref="refundForm" :model="refundForm" status-icon label-position="left" label-width="100px"
        style="width: 400px; margin-left:50px;">
        <el-form-item :label="refundTitle" prop="refundMoney">
          <el-input v-model="refundForm.refundMoney" :disabled="true" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain1 round icon="el-icon-error" @click="refundDialogVisible = false">{{ $t('Cancel') }}</el-button>
        <el-button plain1 round icon="el-icon-success" type="primary" @click="confirmRefund">{{ $t('Confirm') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listOrder, shipOrder, refundOrder } from '@/api/order'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import checkPermission from '@/utils/permission' // 权限判断函数
import { allForPerm } from '@/api/shop'
import { formatDate } from '@/utils/date'
import {userOption} from "@/api/user";




export default {
  name: 'orderList',
  components: { Pagination },
  filters: {

  },
  data() {
    const startDate = formatDate(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7), 'yyyy-MM-dd')
    const endDate = formatDate(new Date(), 'yyyy-MM-dd')
    const statusMap = {
      101: this.$t('Unpaid1'),
      102: this.$t('Member_cancelled'),
      103: this.$t('System_cancelled'),
      201: this.$t('Paid')+'✓',
      202: this.$t('Apply_for_refund'),
      203: this.$t('Refunded'),
      301: this.$t('Sent_for_delivery'),
      401: this.$t('Member_received'),
      402: this.$t('System_received')
    }

    // const statusMap = {
    //   0: this.$t('New'),
    //   1: this.$t('Hangup'),
    //   2: this.$t('Unpaid'),
    //   3: this.$t('Ongoing'),
    //   4: this.$t('Meal_taken'),
    //   5: this.$t('Completed'),
    //   6: this.$t('Cancelled')
    // }

    const payTypeMap = {
      1: this.$t('现金支付'),
      2: this.$t('礼物卡支付'),
      3: this.$t('PayPal支付'),
      4: this.$t('余额支付'),
      5: this.$t('Clover支付'),
      6: this.$t('积分支付'),
      7: this.$t('未支付')
    }

    const orderSourceMap = {
      1: this.$t('APP'),
      2: this.$t('门店下单'),
      3: this.$t('官网商城'),
      4: this.$t('客户订阅')
    }

    const orderTypeMap = {
      1: this.$t('自提'),
      2: this.$t('配送'),
      3: this.$t('堂食'),
      4: this.$t('外带')
    }

    return {
      statusMap,
      payTypeMap,
      orderSourceMap,
      list: [],
      total: 0,
      listLoading: true,
      userOptions: [],
      listQuery: {
        page: 1,
        limit: 20,
        payType:[],
        orderSource:[],
        userId: undefined,
        shopId: undefined,
        orderStatusArray: [],
        startDate: undefined,
        endDate: undefined,
        dateRange:[],
      },
      payTypes:[{value: 1, label: '现金支付'},
        {value: 2, label: '礼物卡支付'},
        {value: 3, label: 'PayPal支付'},
        {value: 4, label: '余额支付'},
        {value: 5, label: 'Clover支付'},
        {value: 6, label: '积分支付'},],
      orderSources:[{value: 1, label: 'APP'},{value: 2, label: '门店下单'}],
      totalRange: [],
      orderDialogVisible: false,
      orderDetail: {
        order: {},
        user: {},
        orderGoods: []
      },
      shipForm: {
        orderId: undefined,
        shipChannel: undefined,
        shipSn: undefined
      },
      shipDialogVisible: false,
      refundForm: {
        orderId: undefined,
        refundMoney: undefined,
        points: undefined
      },
      refundDialogVisible: false,
      downloadLoading: false,
      shops: [],
      refundTitle: undefined,
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一小时',
            onClick(picker) {
              const end = new Date();
              const start = new Date(end.getTime() - 3600 * 1000);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '今天',
            onClick(picker) {
              const start = new Date(new Date().setHours(0, 0, 0));
              const end = new Date();
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近7天',
            onClick(picker) {
              const end = new Date();
              const start = new Date(end.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      }
    }
  },
  created() {
    if (this.$route.query && this.$route.query.id) {
      this.listQuery.id = this.$route.query.id
    }
    if (this.$route.query && this.$route.query.shopId) {
      this.listQuery.shopId = this.$route.query.shopId
    }
    this.getList()
    this.getUserList()
    allForPerm().then(response => {
      this.shops = response.data.data.list
    })
  },
  methods: {
    getUserList() {
      userOption()
        .then(response => {
          this.userOptions = response.data.data
        })
        .catch(() => {
          this.userOptions = []
        })
    },
    changeDate(value) {
      if (value === null) {
        this.totalRange = [];
      }
      this.getList();
    },
    orderStatusFilter(status) {
      return this.statusMap[status]
    },
    payTypeFilter(type) {
      return this.payTypeMap[type]
    },
    orderSourceFilter(source) {
      return this.orderSourceMap[source]
    },
    orderTypeFilter(type) {
      return this.orderTypeMap[type]
    },
    checkPermission,
    getList() {
      this.listLoading = true
      this.listQuery.startDate = this.totalRange[0];
      this.listQuery.endDate = this.totalRange[1];
      listOrder(this.listQuery).then(response => {
        this.list = response.data.data.list
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleDetail(row) {
      this.$router.push({ path: '/order/detail', query: { id: row.id } })
      /*        detailOrder(row.id).then(response => {
          this.orderDetail = response.data.data
        })
        this.orderDialogVisible = true*/
    },
    handleShip(row) {
      this.shipForm.orderId = row.id
      this.shipForm.shipChannel = row.shipChannel
      this.shipForm.shipSn = row.shipSn

      this.shipDialogVisible = true
      this.$nextTick(() => {
        this.$refs['shipForm'].clearValidate()
      })
    },
    priceOrPoint(row) {
      if (row.payType == 6) {
        return row.points + 'pts'
      } else {

        return "$" + row.actualPrice
      }
    },
    confirmShip() {
      this.$refs['shipForm'].validate((valid) => {
        if (valid) {
          shipOrder(this.shipForm).then(response => {
            this.shipDialogVisible = false
            this.$notify.success({
              title: this.$t('Success!'),
              message: this.$t('Confirm_delivery_successful')
            })
            this.getList()
          }).catch(response => {
            this.$notify.error({
              title: this.$t('Failed'),
              message: this.$t(response.data.errmsg)
            })
          })
        }
      })
    },
    handleRefund(row) {
      this.refundForm.orderId = row.id
      this.refundForm.refundMoney = row.payType == 6 ? row.points : row.orderPrice;
      this.refundTitle = row.payType == 6 ? this.$t('退款积分') : this.$t('Refunded_amount')
      this.refundDialogVisible = true
      this.$nextTick(() => {
        this.$refs['refundForm'].clearValidate()
      })
    },
    confirmRefund() {
      this.$refs['refundForm'].validate((valid) => {
       this.$refs['handleRefund'].icon='el-icon-loading'
        if (valid) {
          this.refundDialogVisible = false
          refundOrder(this.refundForm).then(response => {
            this.$refs['handleRefund'].icon='el-icon-refresh-left'
            this.$notify.success({
              title: this.$t('Success!'),
              message: '确认退款成功'
            })
            this.getList()
          }).catch(response => {
            this.$notify.error({
              title: this.$t('Failed'),
              message: this.$t(response.data.errmsg)
            })
          })
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['订单ID', '订单编号', '用户ID', '订单状态', '是否删除', '收货人', '收货联系电话', '收货地址']
        const filterVal = ['id', 'orderSn', 'userId', 'orderStatus', 'isDelete', 'consignee', 'mobile', 'address']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '订单信息')
        this.downloadLoading = false
      })
    },
    getShopName(shopId) {
      let shop = this.shops.find(shop => {
        if (shop.id == shopId) {
          return true
        }
      })
      if (shop) {
        return shop.name
      }
    },
    getIndex(index) {
      return (index + 1) + (this.listQuery.page - 1) * this.listQuery.limit;
    }
  }
}
</script>
<style>
  .el-descriptions__body .el-descriptions__table .el-descriptions-item__cell {
    text-align: center;
  }
</style>
